package blogsys.demo.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * jwt工具
 * 2022.5.14
 * @author xp
 * @version 1.0
 */
public class JwtUtils {
    public static final long EXPIRE = 1000 * 60 * 60 * 24; //token过期时间   24小时
    public static final String APP_SECRET = "71515xp";  //密钥

    /**
     * 生成token
     * @param id
     * @return JwtToken
     */
    public static String setJwtToken(String id){
        String JwtToken = Jwts.builder()
                .setHeaderParam("typ", "JWT") // 头参数
                .setSubject("server")  //签发者
                .setIssuedAt(new Date()) //签发时间
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .claim("id", id) //用户账号
                .signWith(SignatureAlgorithm.HS256, APP_SECRET) //加密算法 秘钥
                .compact();

        return JwtToken;
    }


    /**
     * 从请求头中获取token 并解析验证
     * @param request
     */
    public static boolean checkToken(HttpServletRequest request) {
        try {
            String jwtToken = request.getHeader("token");
            if(jwtToken == null){
                return false; //不携带token
            }
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 从token中获取账号(id)
     *
     *
     * token 获取不到
     * @return id
     */
    public static String getIdByJwtToken(HttpServletRequest request) {
        String jwtToken = request.getHeader("token");
//<<<<<<< HEAD

        System.out.println(jwtToken+"token:================");
//=======
//>>>>>>> 936a29b27488f099f00d4bedf92811842ac5da04
        if(jwtToken == null){
            return "";
        }
        try {
            // 这里解析可能会抛异常，所以try catch来捕捉
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);

            Claims claims = claimsJws.getBody();

            System.out.println("============"+"解析成功");
            String  id = (String) claims.get("id");
            return id;
        }catch (Exception e){
            return "";
        }
    }
}
